<template>
  <sweet-select-tree
    ref="datasourceTree"
    node-key="id"
    v-model="checkeData"
    :data="data"
    :defaultProps="defaultProps"
    :filterable="true"
    :clearable="true"
    @change="change"
  >
    <template #default="{data: {label}}"> {{ label }}<span style="color: gray">(suffix)</span></template>
  </sweet-select-tree>
  <sweet-form :rules="rules" :model="formData">
    <sweet-form-item prop="value">
      <sweet-select-tree
        ref="datasourceTree"
        node-key="id"
        :data="data"
        :defaultProps="defaultProps"
        :filterable="true"
        :clearable="true"
        @change="change"
      ></sweet-select-tree>
    </sweet-form-item>
  </sweet-form>
</template>

<script lang="ts">
export default {
  name: 'demo',
  data() {
    return {
      checkeData: 3,
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      rules: {
        value: [{validator: this.validator, trigger: ['blur', 'change'], required: true}]
      },
      formData: {value: ''},
      checkedKeys: [3],
      data: [
        {
          id: 1,
          label: '一级 1',
          children: [
            {
              id: 2,
              label: '二级 1-1',
              children: [{id: 3, label: '三级 1-1-1'}]
            }
          ]
        },
        {
          id: 4,
          label: '一级 2',
          children: [
            {
              id: 5,
              label: '二级 2-1',
              children: [{id: 6, label: '三级 2-1-1'}]
            },
            {
              id: 7,
              label: '二级 2-2',
              children: [{id: 8, label: '三级 2-2-1'}]
            }
          ]
        },
        {
          id: 9,
          label: '一级 3',
          children: [
            {
              id: 10,
              label: '二级 3-1',
              children: [{id: 11, label: '三级 3-1-1'}]
            },
            {
              id: 12,
              label: '二级 3-2',
              children: [{id: 13, label: '三级 3-2-1'}]
            }
          ]
        }
      ]
    };
  },
  methods: {
    change(data) {
      console.log('modelValue: ', this.checkeData);
      console.log(data, 'data');
      this.formData.value = data?.keys;
    },
    validator(rule, value, callback) {
      console.log('validate');
      if (!this.formData.value) {
        callback(new Error('必填項'));
      }
    }
  }
};
</script>
